const express = require("express");
const router = express.Router();
const multer = require('multer');
const path = require('path')

let destinationFilePath =  path.join(__dirname,'../public/uploads')
//配置diskStorage来控制文件存储的位置以及文件名字等
var storage = multer.diskStorage({
    //确定图片存储的位置
    destination(req, file, callback){   
        console.log(req.body,req.params,req.query,file)     
        callback(null, destinationFilePath)
    },
    
    //确定图片存储时的名字,注意，如果使用原名，可能会造成再次上传同一张图片的时候的冲突
    filename(req, file, callback){
        callback(null, Date.now() + "-" + file.originalname )  // 
    }
});
//生成的专门处理上传的一个工具，可以传入storage、limits等配置
var upload = multer({storage: storage});
//接收上传图片请求的接口



 
//单个文件上传  
router.post('/single',upload.single('singleFile'),  (req, res) => {
    //图片已经被放入到服务器里,且req也已经被upload中间件给处理好了（加上了file等信息）
    //线上的也就是服务器中的图片的绝对地址
    console.log(req.file);
    var url = '/uploads/' + req.file.filename
    res.json({
        code: 200,
        type: 'single',
        originalname: req.file.originalname,
        path: req.file.path,
        url: url 
    })
});
 
//多个文件上传
router.post('/multer', upload.array('multerFile'), (req, res) => {
    console.log(req.files);
    let fileList = [];
    req.files.map((elem) => {
        fileList.push({
            originalname: elem.originalname
        })
    });
    res.json({
        code: "200",
        type: 'multer',
        fileList: fileList
    });
}); 
module.exports = router;